package com.examination.client.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.examination.client.domian.dto.UserInfoDTO;
import com.examination.client.entity.SystemUserPermission;
import com.examination.client.entity.UserInfo;
import com.examination.client.enums.DeleteStatusEnum;
import com.examination.client.mapper.SystemUserPermissionInfoMapper;
import com.examination.client.service.IUserMenuService;
import com.examination.client.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class IUserMenuServiceImpl extends ServiceImpl<SystemUserPermissionInfoMapper, SystemUserPermission> implements IUserMenuService {

    @Override
    public Boolean save(UserInfo userInfo, List<Integer> menuList) throws Exception {
        log.info("IUserMenuServiceImpl save ------- > ");
        List<SystemUserPermission> systemUserPermissionList = new ArrayList<>();
        for (int i = 1; i < 7; i ++) {
            SystemUserPermission systemUserPermission = new SystemUserPermission();
            systemUserPermission.setUserId(userInfo.getUserId());
            systemUserPermission.setSystemUserMenuId(i);
            if (menuList != null && menuList.contains(i)) {
                systemUserPermission.setSelectStatus(1);
            } else {
                systemUserPermission.setSelectStatus(0);
            }
            systemUserPermission.setCreateTime(new Date());
            systemUserPermissionList.add(systemUserPermission);
        }
        log.info(JsonUtils.toJson(systemUserPermissionList));
        return saveBatch(systemUserPermissionList);
    }

    @Override
    public Boolean modify(UserInfoDTO userInfoDTO) throws Exception {
        log.info("IUserMenuServiceImpl modify ------- > ");
        List<SystemUserPermission> systemUserPermissionList = findByUserId(userInfoDTO.getUserId() + "");
        for (int i = 0; i < systemUserPermissionList.size(); i ++) {
            SystemUserPermission systemUserPermission = systemUserPermissionList.get(i);
            if (userInfoDTO.getMenuList() != null && userInfoDTO.getMenuList().contains(systemUserPermission.getSystemUserMenuId())) {
                systemUserPermission.setSelectStatus(1);
            } else {
                systemUserPermission.setSelectStatus(0);
            }
        }
        log.info(JsonUtils.toJson(systemUserPermissionList));
        return updateBatchById(systemUserPermissionList);
    }

    @Override
    public List<SystemUserPermission> findByUserId(String userId) {
        LambdaQueryWrapper<SystemUserPermission> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(SystemUserPermission::getUserId, userId);
        return list(queryWrapper);
    }

}
